package utils

import (
	"fmt"
	"imooc.com/demo-lottery/comm"
	"imooc.com/demo-lottery/datasource"
	"log"
	"math"
	"time"
)

const userFrameSize = 2

func init() {}

func resetGroupUserList() {
	log.Println("user_day_lucky.resetGroupUserList start")
	rds := datasource.InstanceCache()
	for i := 0; i < userFrameSize; i++ {
		key := fmt.Sprintf("day_users_%d", i)
		rds.Do("DEL", key)
	}
	log.Println("user_day_lucky.resetGroupUserList stop")

	// 零点归零的定时期
	time.AfterFunc(comm.NextDayDuration(), resetGroupIpList)
}

func IncrUserLuckyNum(uid int) int64 {
	i := uid % userFrameSize
	key := fmt.Sprintf("day_users_%d", i)
	rds := datasource.InstanceCache()
	rs, err := rds.Do("HINCRBY", key, uid, 1)
	if err != nil {
		log.Printf("user_day_lucky.IncrUserLuckyNum "+
			"HINCRBY key=%s, uid=%d, error=%s\n", key, uid, err)
		return math.MaxInt32
	} else {
		num := rs.(int64)
		return num
	}
}

func InitUserLuckyNum(uid int, num int64) {
	if num <= 0 {
		return
	}
	i := uid % userFrameSize
	key := fmt.Sprintf("day_users_%d", i)
	rds := datasource.InstanceCache()
	_, err := rds.Do("HSET", key, uid, num)
	if err != nil {
		log.Printf("user_day_lucky.InitUserLuckyNum "+
			"HSET key=%s, uid=%d, error=%s\n", key, uid, err)
	}
}
